﻿using UnityEngine;
using QFramework;
using UnityEngine.EventSystems;

namespace HKTools
{
    /// <summary>
    /// HK_FirstPersonCam 角色总控脚本
    /// </summary>
    public class HK_FirstPersonCtrl : HKFirstPersonCam_BaseController
    {
        [Header("是否左键控制相机？"), SerializeField] bool isLeftMouseCtrl;

        [Header("是否开启UI遮挡？"), SerializeField] bool isUIBlock;

        [Header("基础移动速度："), SerializeField] float moveSpeed = 6f;
        [Header("重力加速度："), SerializeField] float gravity = 9.81f;
        [Header("跳跃高度："), SerializeField] float jumpHeight = 1f;

        [Header("地面检测点："), SerializeField] Transform groundCheck;
        [Header("地面检测半径："), SerializeField] float groundDistance = 0.3f;
        [Header("地面检测层级："), SerializeField] LayerMask groundMask;

        CharacterController controller;
        HK_FirstPersonCamLook firstPersonCamLook;
        Vector3 velocity;
        bool isGrounded;
        bool isSpeedUp;

        void Awake()
        {
            controller = GetComponent<CharacterController>();

            if (controller == null)
                HKDebug.LogError("未找到CharacterController组件，请检查挂载对象");

            firstPersonCamLook = GetComponentInChildren<HK_FirstPersonCamLook>();

            if (firstPersonCamLook == null)
                HKDebug.LogError("未找到子对象中的HK_FirstPersonCamLook组件");

            firstPersonCamLook.Init(isLeftMouseCtrl, isUIBlock);
        }

        void Start()
        {
            this.GetSystem<IHK_FirstPersonCamSystem>().InitFirstPersonCam(this);
        }

        void Update()
        {
            // UI遮挡检测
            if (isUIBlock && EventSystem.current?.IsPointerOverGameObject() == true)
                return;

            if (controller == null || !controller.enabled)
                return;

            // 地面检测
            isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

            if (isGrounded && velocity.y < 0)
            {
                velocity.y = -2f;
            }

            // 加速状态判断
            isSpeedUp = Input.GetKey(KeyCode.LeftShift);

            float speedMultiplier = isSpeedUp ? 3f : 1f;
            float x = Input.GetAxis("Horizontal");
            float z = Input.GetAxis("Vertical");

            Vector3 motion = transform.right * x + transform.forward * z;

            controller.Move(motion * moveSpeed * speedMultiplier * Time.deltaTime);

            if (Input.GetButtonDown("Jump") && isGrounded)
            {
                velocity.y = Mathf.Sqrt(jumpHeight * 2f * gravity);
            }

            velocity.y -= gravity * Time.deltaTime;
            controller.Move(velocity * Time.deltaTime);
        }

        public void ChangeRot(Transform pos_TF)
        {
            transform.rotation = Quaternion.Euler(0, pos_TF.eulerAngles.y, 0);
            firstPersonCamLook.ResetRot();
        }

        public void ResetRot()
        {
            firstPersonCamLook.ResetRot();
        }

        void OnTriggerEnter(Collider other)
        {
            // 尝试获取触发点标识组件（假设每个触发点有 HK_FirstPersonTrigger 组件）
            if (other.TryGetComponent<HK_FirstPersonTrigger>(out var trigger))
            {
                // 通过事件系统发送触发事件
                this.GetSystem<IHK_FirstPersonCamSystem>().ChangeFirstPersonTrigger(trigger);
            }
        }
    }
}